from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text, desc, func
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlmodel import Field, SQLModel
from typing import List

class MetroKVBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    type: str = Field(sa_column=Column(String(length=255), default=''), description='类型')
    key: str = Field(sa_column=Column(String(length=255), default=''), description='key')
    value: str = Field(sa_column=Column(MEDIUMTEXT),description='value 存储各种信息')
    create_time: Optional[datetime] = Field(
        sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))
    update_time: Optional[datetime] = Field(sa_column=Column(DateTime,
                                                             nullable=False,
                                                             index=True,
                                                             server_default=text('CURRENT_TIMESTAMP'),
                                                             onupdate=text('CURRENT_TIMESTAMP')))

class MetroKV(MetroKVBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)


class MetroKVDao:
    @staticmethod
    def create_metro_kv(metro_kv: MetroKV) -> MetroKV:
        with session_getter() as session:
            # 确保 metro_kv 有一个 UUID
            if not metro_kv.id:
                metro_kv.id = uuid4()

            session.add(metro_kv)
            session.commit()
            session.refresh(metro_kv)
            return metro_kv


    @staticmethod
    def get_v_by_type_and_key(type: str, key: str) -> Optional[MetroKV]:
        if not key:  # key 不允许为空
            return None

        with session_getter() as session:
            # 基础查询对象
            query = session.query(MetroKV)

            # 动态添加过滤条件
            if type:  # type 非空时添加 type 条件
                query = query.filter(MetroKV.type == type)

            # 始终添加 key 条件（key 已保证非空）
            query = query.filter(MetroKV.key == key)

            # 获取结果（根据实际情况选择）
            return query.one_or_none()

